import { createBrowserRouter, Navigate, useLocation } from "react-router-dom";
import React from "react";

import App from "../App";
import Home from "../pages/home/Index";
import Index from "../pages/index/Index";
import Login from "../pages/login/Index";
import Register from "../pages/register/Index";
import Set from "../pages/set/Index";
import Num from "../pages/num/Index";
import Order from "../pages/order/Index";
import Mode from '../pages/mode/Index';
import View from '../pages/view/Index';
import AI from '../pages/AI/Index';
import DocsIndex from '../pages/docs/Index';
import Guide from '../pages/docs/Shi'
import Faq from '../pages/docs/Chang'
import Worker from '../pages/worker/Index';
import Zhi from '../pages/zhi/Index'

export const tworouter = [
  {
    path: "/home",
    element: <Home></Home>,
    title: "首页",
   
  },
  {
    path: "/view",
    element: <View></View>,
    title: "可视大屏",
    children: [
      {
        path: "/view/index",
        element: <Index></Index>,
        title: "数据大屏",
      },
    ],
  },
  {
     path: "/zhi",
        element: <Zhi></Zhi>,
        title: "智能体",
  },
  {
    path: "/docs",
    element: <DocsIndex></DocsIndex>,
    title: "知识中心",
    children: [
      {
        path: "/docs/guide",
        element: <Guide></Guide>,
        title: "使用指南",
      },
      {
        path: "/docs/faq",
        element: <Faq></Faq>,
        title: "常见问题",
      },
    ],
  },
  {
    path: "/worker",
    element: (
      <AdminRoute>
        <Worker></Worker>
      </AdminRoute>
    ),
    title: "创作中心",
  },
 {
    path: "/AI",
    element: <AI></AI>,
    title: "AI智能",
 },
  {
    path: "/order",
    element: (<Order />),
    title: "后台管理",
  },
  {
    path: "/set",
    element: (<Set />),
    title: "系统设置",
  },
  
];

export const router = createBrowserRouter([
  {
    path: "/",
    element: <App></App>,
    children: tworouter,
  },
  {
    path: "/login",
    element: <Login></Login>,
  },
  {
    path: "/register",
    element: <Register></Register>,
  },
  {
    path: "/mode",
    element: <Mode></Mode>,
  },
   {
    path: "/num",
    element: <Num></Num>,
    
  },
]);

export default router;

// ========== Minimal RBAC Guard ==========
function AdminRoute({ children }: { children: React.ReactNode }) {
  const location = useLocation()
  let role: string | null = null
  try {
    const raw = localStorage.getItem('auth_user')
    role = raw ? (JSON.parse(raw)?.role || null) : null
  } catch {
    role = null
  }
  if (role !== 'admin') {
    return <Navigate to="/home" replace state={{ from: location.pathname }} />
  }
  return <>{children}</>
}
